package com.moyun.zbmy.zizhou.ui.fragment;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.moyun.zbmy.zizhou.R;
import com.moyun.zbmy.zizhou.application.Constances;
import com.moyun.zbmy.zizhou.beans.AccountNewsItem;
import com.moyun.zbmy.zizhou.beans.AccountNewsVo;
import com.moyun.zbmy.zizhou.beans.SingleResult;
import com.moyun.zbmy.zizhou.beans.Titles;
import com.moyun.zbmy.zizhou.http.AbsListNetCallback;
import com.moyun.zbmy.zizhou.http.AbsNetCallBack;
import com.moyun.zbmy.zizhou.http.NetUtils;
import com.moyun.zbmy.zizhou.http.ParamsEditor;
import com.moyun.zbmy.zizhou.ui.activities.AccountKnockOutDetailActivity;
import com.moyun.zbmy.zizhou.ui.activities.AccountNewsDetailActivity;
import com.moyun.zbmy.zizhou.ui.adapter.AttentionAdapter;
import com.moyun.zbmy.zizhou.ui.adapter.holder.AttentionMoreImgNewsHolder;
import com.moyun.zbmy.zizhou.ui.adapter.holder.AttentionNewsHolder;
import com.moyun.zbmy.zizhou.ui.adapter.holder.BaseAbsHolder;
import com.moyun.zbmy.zizhou.ui.util.IListShowData;
import com.moyun.zbmy.zizhou.ui.utils.DataUtils;
import com.moyun.zbmy.zizhou.utils.UserManager;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;

import static android.app.Activity.RESULT_OK;

/**
 * 互动号详情---新闻列表
 */
public class AccountDetailNewsFragment extends ColumnBaseFragment implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, AttentionAdapter.OnAttentionNewsClickListener {
    @BindView(R.id.refreshlayout)
    protected CanRefreshLayout mRefreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView mRecyclerView;
    public static final String ACCOUNT_ID = "account_id";
    public static final String NEWS_TYPE = "news_type";
    protected static final int CODE_REQUEST_DETAIL = 112;
    private int type = 1;// 1,查询全部，2查询视频，3查询文章（普通的非动态新闻）
    private String accountId = "";
    private AttentionAdapter mAdapter;
    private int mPageNo = 0;
    private boolean mIsLoading = false;
    private int mPageAll = 0;
    private List<IListShowData> dataList = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_account_news_list, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setOnLoadMoreListener(this);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
//        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        Bundle arguments = getArguments();
        if (arguments != null) {
            type = arguments.getInt(NEWS_TYPE, 1);
            accountId = arguments.getString(ACCOUNT_ID);
        }
    }

    @Override
    protected boolean onFragmentShow(boolean isFirst, boolean isCallFromResume) {
        if (isFirst) {
            mRefreshLayout.autoRefresh();
        }
        return super.onFragmentShow(isFirst, isCallFromResume);
    }

    @Override
    public void onLoadMore() {
        mPageNo++;
        getData();
    }

    @Override
    public void onRefresh() {
        if (mIsLoading) {
            return;
        }
        dataList.clear();
        mPageNo = 0;
        mIsLoading = true;
        getData();
    }

    /**
     * 设置是否可以下拉刷新
     *
     * @param isEnable
     */
    public void setRefreshLayoutRefreshEnable(boolean isEnable) {
        mRefreshLayout.setRefreshEnabled(isEnable);
    }

    private void getData() {
        if (!TextUtils.isEmpty(accountId)) {
            String token = "";
            String userId = "";
            if (null != UserManager.getInstance().getUser()) {
                token = UserManager.getInstance().getUser().getToken();
                userId = UserManager.getInstance().getUser().getUserId();
            }
            Map<String, Object> param = new HashMap<>();
            param.put("siteNumber", Constances.SITE_ID);
            param.put("userId", userId);
            param.put("token", token);
            param.put("index", "" + mPageNo);
            param.put("capacity", "10");
            param.put("followedId", accountId);
            param.put("type", type);

            NetUtils.getNetAdapter().getAccountNewsList(getOwnerName(), param, new AbsNetCallBack<AccountNewsVo>(AccountNewsVo.class) {
                @Override
                public void onSuc(AccountNewsVo listVo) {
                    if (null != listVo && ListUtils.isListValued(listVo.getResultList())) {
                        dataList.addAll(listVo.getResultList());
                        mPageAll = listVo.getPageAll();
                    }
                }

                @Override
                public void onError(Throwable ex, String errorMsg) {
                    if (mPageNo >= 1) {
                        mPageNo--;
                    }
                }

                @Override
                public void onEnd() {
                    onNetFinish();
                    initData();
                }
            });

        } else {
            onNetFinish();
        }

    }

    private void initData() {
        if (mAdapter == null) {
            mAdapter = new AttentionAdapter(getActivity(), dataList, null, this);
            mRecyclerView.setAdapter(mAdapter);
        } else {
            mAdapter.setData(dataList);
        }

    }

    private synchronized void onNetFinish() {
        mIsLoading = false;
        mRefreshLayout.refreshComplete();
        mRefreshLayout.loadMoreComplete();
        mRefreshLayout.setLoadMoreEnabled(mPageNo+1 >= mPageAll ? false : true);
    }


    @Override
    public void OnItemClick(AccountNewsItem temp, int type) {
        if (type == AttentionAdapter.VIEWTYPE_NEWS_ITEM) {
            Intent intent = new Intent(getContext(), AccountNewsDetailActivity.class);
            intent.putExtra(AccountNewsDetailActivity.NEWS_BEAN, temp);
            this.startActivityForResult(intent,CODE_REQUEST_DETAIL);
        } else if (type == AttentionAdapter.VIEWTYPE_NEWS_IMG_ITEM) {
            Intent intent = new Intent(getContext(), AccountKnockOutDetailActivity.class);
            intent.putExtra(AccountKnockOutDetailActivity.NEWS_BEAN, temp);
            this.startActivityForResult(intent, CODE_REQUEST_DETAIL);
        }
    }

    @Override
    public void OnItemAccountClick(AccountNewsItem temp) {
        //TODO 进入互动账号详情
    }

    @Override
    public void OnItemCommentClick(AccountNewsItem temp, int position) {
        //TODO 新闻评论
    }

    @Override
    public void OnItemDiggClick(AccountNewsItem temp, int position) {
        //TODO 新闻点赞
        //TODO 新闻点赞
        if (null != UserManager.getInstance().getUser()) {
            doUp(temp, position);
        } else {
            toLogin();
        }
    }

    @Override
    public void OnItemAttentionClick(AccountNewsItem temp, int position) {
        //TODO 去关注
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == CODE_REQUEST_DETAIL) {
                mRefreshLayout.autoRefresh();
            }
        }
    }


    private BaseAbsHolder diggHolder = null;

    private void doUp(final AccountNewsItem temp, final int position) {
        ParamsEditor pe = new ParamsEditor();
        pe.put("dynamicId", temp.getNewsDetailId());
        pe.put("fType", 3);//1 主播 2报料 3新闻 4 直播 5视频
        pe.put("userId", UserManager.getInstance().getUser().getUserId());

        RecyclerView.LayoutManager manager = mRecyclerView.getLayoutManager();
        View lastView = manager.findViewByPosition(position);

        if (null != lastView) {
            if (mRecyclerView.getChildViewHolder(lastView) instanceof AttentionNewsHolder) {
                diggHolder = (AttentionNewsHolder) mRecyclerView.getChildViewHolder(lastView);
                if (null != diggHolder) {
                    ((AttentionNewsHolder) diggHolder).getAttentionNewsDigg().setDrawableEnlarge();
                }
            } else if (mRecyclerView.getChildViewHolder(lastView) instanceof AttentionMoreImgNewsHolder) {
                diggHolder = (AttentionMoreImgNewsHolder) mRecyclerView.getChildViewHolder(lastView);
                if (null != diggHolder) {
                    ((AttentionMoreImgNewsHolder) diggHolder).getAttentionNewsDigg().setDrawableEnlarge();
                }
            }
        }

        NetUtils.getNetAdapter().doUpForDynamics(getOwnerName(), pe.getEncryptedParams(UserManager.getInstance().getToken()), new AbsNetCallBack<SingleResult>(SingleResult.class) {
            @Override
            public void onError(Throwable ex, String errorMsg, int netCode) {
                super.onError(ex, errorMsg, netCode);
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }

            @Override
            public void onSuc(SingleResult singleResult) {
                if (singleResult.isSuccess() && null != diggHolder) {
                    CustomFontTextView diggView = null;
                    if (diggHolder instanceof AttentionNewsHolder) {
                        diggView = ((AttentionNewsHolder) diggHolder).getAttentionNewsDigg();
                    } else if (diggHolder instanceof AttentionMoreImgNewsHolder) {
                        diggView = ((AttentionMoreImgNewsHolder) diggHolder).getAttentionNewsDigg();
                    }
                    if (null != diggView && mAdapter.getItem(position) instanceof AccountNewsItem) {
                        AccountNewsItem newsItem = (AccountNewsItem) mAdapter.getItem(position);

                        if (newsItem.isNewsDetailAttitudesStatus()) {
                            newsItem.setNewsDetailAttitudesStatus(false);
                            newsItem.setNewsDetailAttitudesCount(newsItem.getNewsDetailAttitudesCount() - 1);

                            Drawable drawable = getResources().getDrawable(R.mipmap.icon_compere_btn_normal);
                            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                            diggView.setDrawables(drawable, null, null, null);
                            diggView.setTextColor(getResources().getColor(R.color.colorOpinionSelectNo));
                        } else {
                            newsItem.setNewsDetailAttitudesStatus(true);
                            newsItem.setNewsDetailAttitudesCount(newsItem.getNewsDetailAttitudesCount() + 1);

                            Drawable drawable = getResources().getDrawable(R.mipmap.icon_compere_btn_press);
                            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                            diggView.setDrawables(drawable, null, null, null);
                            diggView.setTextColor(getResources().getColor(R.color.colorTxRedMain_));
                            addInvitation(Constances.ADD_INTEGRAL_DOUP);
                        }

                        long upCount = newsItem.getNewsDetailAttitudesCount();
                        if (upCount > 0) {
                            diggView.setText(String.valueOf(upCount));
                        } else {
                            diggView.setText("点赞");
                        }
                    }
                }


            }
        });
    }
}
